package com.develope.menu.service;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;

import com.develope.menu.Constant.ERROR;
import com.develope.menu.utils.Logger;

public class AsyncSoapTask extends AsyncTask<String, Void, String> {
	private int errorCode = ERROR.UNKNOWN;
	private HttpHandler httpHandler;

	public AsyncSoapTask(HttpHandler httpHandler) {
		this.httpHandler = httpHandler;
	}

	@Override
	protected String doInBackground(String... arg0) {
		SoapObject request = new SoapObject(SoapHelper.NAMESPACE,
				httpHandler.operation);
		if (httpHandler.params != null) {
			for(int i=0;i<httpHandler.params.length;i++)
			{
			request.addProperty(httpHandler.params[i]);
			}
		}
		if (httpHandler.param != null) {
			request.addProperty(httpHandler.param);
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.setOutputSoapObject(request);

		HttpTransportSE httpTransport = new HttpTransportSE(SoapHelper.URL);
		String response = null;
		try {
			httpTransport.call(SoapHelper.getAction(httpHandler.operation), envelope);
			// response = envelope.getResponse();
			SoapPrimitive soapResponse = (SoapPrimitive)envelope.getResponse();
			response = soapResponse.toString();
			errorCode = ERROR.OK;
		} catch (Exception exception) {
			response = exception.toString();
		}
		
		return response.toString();
	}

	@Override
	protected void onPostExecute(String result) {
		if (result == null) {
			Logger.error("[ERR] httpTask: onPostExcute, the result is undefined!");
		}
		// TODO: post data to GUI
		httpHandler.onResponse(errorCode, result);
	}

}
